package com.system.module.system.controller;

import com.system.common.request.SysUserRegisterRequest;
import com.system.common.utils.ServletUtils;
import com.system.framework.security.LoginRequest;
import com.system.framework.security.LoginUser;
import com.system.framework.security.service.SysLoginService;
import com.system.framework.security.service.SysPermissionService;
import com.system.framework.security.service.TokenService;
import com.system.framework.web.domain.Result;
import com.system.module.system.entity.SysMenu;
import com.system.module.system.entity.SysUser;
import com.system.module.system.service.ISysMenuService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author 程序员Mars
 */
@RestController
@AllArgsConstructor
public class SysLoginController {

    private final SysLoginService loginService;

    private final ISysMenuService menuService;

    private final TokenService tokenService;

    /**
     * 登录方法
     *
     * @param loginRequest 登陆信息
     * @return 结果
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest) {
        String token = loginService.login(loginRequest);
        return Result.success(token);
    }


    /**
     * 注册用户
     *
     * @param request 请求参数
     * @return Result
     */
    @PostMapping("/register")
    public Result register(@RequestBody SysUserRegisterRequest request) {
        loginService.register(request.getUsername(), request.getPassword(), request.getMobile(),
                request.getType());
        return Result.success();
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public Result getInfo() {
        return loginService.getUserInfo();
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public Result getRouters() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return Result.success(menuService.buildMenus(menus));
    }
}
